package com.army.stock.service.impl;

import com.army.stock.dao.ArmyUserDao;
import com.army.stock.domain.ArmyUser;
import com.army.stock.service.ArmyUserService;
import com.javalife.common.domain.page.PaginatedArrayList;
import com.javalife.common.util.security.MD5Util;
import org.apache.commons.lang.StringUtils;

import java.util.List;
import java.util.Map;
import java.util.Random;

/**
 * Created by zhangyong on 14/12/25.
 */
public class ArmyUserServiceImpl implements ArmyUserService {

    private ArmyUserDao armyUserDao;

    public void setArmyUserDao(ArmyUserDao armyUserDao) {
        this.armyUserDao = armyUserDao;
    }

    @Override
    public ArmyUser checkLoginUser(String username, String password) {
        if (StringUtils.isBlank(username) || StringUtils.isBlank(password)) {
            return null;
        }
        ArmyUser armyUser = armyUserDao.getArmyUserByUserName(username);
        if (armyUser == null) {
            return null;
        }
        //验证MD5 加密
        if (!MD5Util.digest(password + armyUser.getSalt()).equals(armyUser.getPassword())) {
            return null;
        }
        return armyUser;
    }

    public PaginatedArrayList getArmyUserPageInfo(int currentPage, int pageSize, Map<String, Object> map) {
        int startNum = (currentPage - 1) * pageSize;
        map.put("start", startNum);
        map.put("pageSize", pageSize);
        Integer count = armyUserDao.getCountArmyUser(map);
        List<Map> yearplanItems = armyUserDao.getArmyUserList(map);
        PaginatedArrayList paginatedArrayList = new PaginatedArrayList(currentPage, pageSize);
        paginatedArrayList.setTotalItem(count);
        paginatedArrayList.addAll(yearplanItems);
        return paginatedArrayList;
    }

    public Map getArmyUserById(Long id) {
        return armyUserDao.getArmyUserById(id);
    }

    public ArmyUser getArmyUserEntityById(Long id) {
        return armyUserDao.getArmyUserEntityById(id);
    }

    public void addArmyUser(ArmyUser armyUser) {
        //随机6位数字
        int randomNumber = new Random().nextInt(100000);
        armyUser.setSalt(String.valueOf(randomNumber));
        armyUser.setPassword(MD5Util.digest(armyUser.getPassword() + armyUser.getSalt()));
        armyUserDao.insertArmyUser(armyUser);
    }

    public void updateArmyUser(ArmyUser armyUser) {
        armyUser.setPassword(MD5Util.digest(armyUser.getPassword() + armyUser.getSalt()));
        armyUserDao.updateArmyUser(armyUser);
    }


}
